#!/usr/bin/python

# Project 1a 
# calculator.php

import os, sys, subprocess, time, getopt;
from subprocess import Popen, PIPE, STDOUT,call;

import urllib,urllib2;

# IMPORTANT IF THIS SCRIPT IS NOT RUN FROM ITS OWN DIRECTORY
#    saves caller's directory, changes to script's directory
#    at the end of script, changes back to caller's directory
caller_dir = os.getcwd()
script_dir = sys.path[0]
os.chdir(script_dir)


from helper_functions import *;    	# import helper functions from helper_functions.py
from config import *;        		# loads global variables from config.py
                  

################ Global Variables ####################

USAGE = """UCLA-CS143 - Project 1A Grading Script
         
USAGE: main.py -s <submission_dir> -q <query_parameter> -n <student_id>
	--help
		Displays input options
	-s, --submissions <enter-location-here>
		(Optional)Provide location of students' submission directories.
		System will copy the directory provided to /home/cs143/www/ 
	-q, --queryparam <query_parameter>
		(Optional)Specify different query parameter than config file for testing
	-n, --id <student-id>
		(Optional)System will test only student provided
	
	[ To view/change default values, please see the configuration file (config.py). ]
"""

#CHANGE GLOBAL VARIABLES BASED ON COMMAND-LINE INPUT
try:
	options, remainder = getopt.gnu_getopt(sys.argv[1:], 's:q:n:', ['submissions=','queryparam=','id=','help'])
except getopt.GetoptError, err:
	print str(err)
	print USAGE
	sys.exit(2)

for opt, arg in options:
	if opt in ('-s', '--submissions'):
		print "Removing existing directory /home/cs143/www/submissions"
		if(os.path.exists(submission_folder_abs)):
			os.system('rm -r ' + submission_folder_abs)
		
		print "Moving provided directory to %s" % (arg)
		os.system('cp -r ' + arg + ' ' + submission_folder_abs)
	elif opt in ('-q', '--queryparam'):
		query_parameter = arg
	elif opt in ('-n', '--id'):
		student_id = arg	
	elif opt == '--help':
		print USAGE
		sys.exit(2)
	else:
		print "option %s with value %s is not recognized."	% (opt, arg)
		assert False, "unhandled option"

################ END - Global Variables ####################
              
### CLEAN UP

### PREPARE FOLDER  
if (not os.path.exists(results_dir)):
	os.mkdir(results_dir)
	
	                           
### GRADING FOLDER CHECK
# 1)place the submission folder at ~/www 
# 2)place grading script outside of submissions folder  
           
if os.path.exists(submission_folder_abs) == False:
	print "Please place submission folder into /home/cs143/www directory for grading!\n"
	print "Folder Structure - /home/cs143/www/submissions/[Student_ID]/[Student_Files]\n"
	exit(1) 
                 
# change mode to resolve permission error
os.system('chmod -R 755 ' + submission_folder_abs)

### START GRADING PROCESS  
start_time = time.time()     
print "=== Starting Auto Grading ==="                                            
student_list = []
# store the list of student submission
if(student_id == 0):
	student_list = listdirs(submission_folder_abs);
	student_list.sort()
else:
	student_list.append(student_id)        
	
print "=== Checking Student Submissions ==="
print "Number of directories (submissions) found: ", len(student_list)
          
out = open(result_file, 'w')
out.write(header)
                                      
for sid in student_list:
	
	# PREPARE LOCAL VARIABLES
	comment = "" 
	score = []
	
	for s in range(0,len(test_query)):
		score.append(int(0))
	
	print "== " + sid + " START =="
	
 
	if os.path.isfile(submission_folder_abs + '/' + sid + '/' + test_file) :
		
		test_url_pre = submission_path + submission_folder + "/" + sid + "/" + test_file 
		data = urllib2.urlopen(test_url_pre)
		orig_html = data.read()
		
		# OBTAIN QUERY PARAMETER
		m = re.search('type\s*=\s*"text"\s*name\s*=\s*"\w*"',orig_html,re.I)
		if(m):
			qp = re.sub(r'(?i)type\s*=\s*"\w*"\s*(?i)name\s*=\s*"', '', m.group(0), 0).strip()
			qp = re.sub('"', '', qp, 0).strip() 
		else:
			comment += 'WARNING: UNABLE TO GET QUERY PARAMETER(DEFAULT:' + query_parameter + ' used)'
			qp = query_parameter
			
		# OBTAIN METHOD TYPE
		if(re.search('method\s*=\s*"GET"',orig_html,re.I)):
			method_type = 'GET'
		else:
			method_type = 'POST'
		
		if(method_type == 'GET'):
			for idx in range(0,len(test_query)):
				# reset score counter
				score[idx] = 0
			
				test_url = test_url_pre + "?" + qp + "=" + urllib.quote(test_query[idx])

				data = urllib2.urlopen(test_url)
		    
				s = data.read() 
			                      
				if(test_query_sol[idx] == "error"):
					res = s.find("eval()'d code")
					if(res < 0):
						score[idx] = point_per_case
				else:
					res = s.find(test_query_sol[idx])
					if(res >= 0):
						score[idx] = point_per_case
						
		elif(method_type == 'POST' ):
			for idx in range(0,len(test_query)):
				# reset score counter
				score[idx] = 0
			
				# QUERT BUILDING 
				# expr Parameter
				param = urllib.urlencode({ qp : test_query[idx]})    

				# Comment out either GET or POST request             
				test_url = submission_path + submission_folder + "/" + sid + "/" + test_file 
				data = urllib2.urlopen(test_url, param)

				s = data.read()

				if(test_query_sol[idx] == "error"):
					res = s.find("eval()'d code")
					if(res < 0):
						score[idx] = point_per_case
				else:
					res = s.find(test_query_sol[idx])
					if(res >= 0):
						score[idx] = point_per_case

	else:
		comment += 'ERROR: file does not exist; ' 
	# done of test loop
		
	out.write(sid)
	sum_scores = 0
	for idx in range(0,5):
		sum_scores += score[idx]
		out.write('\t' + str(score[idx]))
	out.write('\t' + str(sum_scores) + '\t' + comment + '\n')
 	print "== " + sid + " DONE =="

#done of student loop     	 
print "=== Project 1a grading is completed ==="
total_time = int(time.time() - start_time)   
print "Auto-Grader Execution Time: ", GetInHMS(total_time)
print "The result file written to ", result_file  

# switch back to the caller's directory
os.chdir(caller_dir)